<!-- 用户管理 -->
<template>
  <div class="newuserManager">
    <div class="con">
      <div class="tree-left">
        <div style="margin-bottom: 5px;">
          <el-input size="medium" placeholder="输入关键字进行过滤" v-model="filterText"> </el-input>
        </div>

        <el-scrollbar style="height:95%;width: 100%;">
          <el-tree :data="dataList" :expand-on-click-node="false" :default-expanded-keys="defaultExpanded"
            :current-node-key='defaultDevice' :props="defaultProps" :highlight-current='true'
            :filter-node-method="filterNode" ref="tree" @node-click="checkItem" node-key="id">
            <span class="custom-tree-node" slot-scope="{node}">
              <img src="../../../public/static/image/elTree/1.9.png" />
              <span style="padding:0px  5px;">{{node.label }}</span>
            </span>
          </el-tree>
        </el-scrollbar>

      </div>


      <div class="right-table">
        <div class="myareaContainer" style="margin-bottom: 8px;height: calc(50% - 4px);" id="myareaContainernoe">
          <div class="Files-top" style="margin-bottom: 20px">
            <div class="ic-left">
              <span>用户管理</span>
            </div>
            <div class="btns">
              <el-button type="primary" @click="addNewUser">添加用户</el-button>
              <el-button type="primary" @click="updateUserInfo">修改用户</el-button>
              <el-button type="danger" @click="deleteUser" class="del-btn last-el-button">删除用户</el-button>
            </div>
          </div>
          <div class="areaContainer">
            <!-- <div class="areaTitle">用户/角色</div> -->
            <div class="usersInfoRole" style="display: flex">
              <!-- <div class="usersInfoList" style="width: calc(100% - 190px);">
										<infoList ref="userInfoList" style="height: 350px;" :columns='columns' :dataList="nowPage" :pageLen='pageLen' :totalSize="nowUnitUserList.length" :checkedFirst="true" @selectPage="nowIndex = $event" :fillAll="true" @clickTableBody="selectUser" @clickTableHead="clickTableHead"></infoList>
									</div> -->
              <el-table :data="nowUnitUserList" ref="singleTable" :selection="selectedRows" highlight-current-row stripe
                :height="heights" border @current-change="handleCurrentChange">
                
                <el-table-column label="序号" width="60" fixed align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.$index + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column v-for='(item,index) in columns' :label="item.name" :key="index">
                  <template slot-scope="scope">
                    <span v-if="item.key=='tokenTime'">{{tokenTimeData[scope.row[item.key]] }}</span>
                    <span v-else>{{ scope.row[item.key] }}</span>
                  </template>
                </el-table-column>
              </el-table>

              <div class="rolesList" :style="{'width':'150px','height':heights+'px','marginLeft':'28px'}">
                <el-scrollbar style="height:100%;width: 100%;">
                  <roleList ref="roleView" :nowCheckedIds="userSelectedRoles" :functionType="0"></roleList>
                </el-scrollbar>
              </div>
            </div>
          </div>
        </div>
        <div class="myareaContainer" style="height: calc(50% - 4px);">
          <div class="tabsHeader">
            <div class="tabBtnsContainer">
              <!-- <button :class="{'tabActive':tabPage == 0}" @click="tabPageChange(0)">用户权限</button>
										<button :class="{'tabActive':tabPage == 1}" @click="tabPageChange(1)">设备权限</button> -->
              <span :class="{'tabActive':tabPage == 0}" @click="tabPageChange(0)">用户权限</span>
              <span :class="{'tabActive':tabPage == 1}" @click="tabPageChange(1)">设备权限</span>
            </div>
            <!-- <button class="saveEditBtn" @click="saveEdit">保存</button> -->
            <el-button type="primary" size="mini" style="margin-right:50px" @click="saveEdit">保存</el-button>
          </div>
          <!-- 用户权限（系统权限、web权限、App权限） -->
          <userRight ref="userRightView" v-show="tabPage == 0"></userRight>
          <!-- 设备权限 （查看设备权限、可操作设备权限）-->
          <userDevice ref="userDeviceView" v-show="tabPage == 1"></userDevice>

        </div>

      </div>
      <!-- 添加用户填写基础信息，选择角色弹窗 -->
      <addNewUserDialog ref="addNewUserDialog"></addNewUserDialog>
      <!-- 新增用户选择设备权限弹窗 -->
      <deviceSelectDialog ref="deviceSelectDialog"></deviceSelectDialog>
      <!-- 新增用户选择用户权限弹窗 -->
      <rightSelectDialog ref="rightSelectDialog"></rightSelectDialog>
      <!-- 修改用户 -->
      <updateUserInfoDialog ref="updateUserInfoDialog" @updateUserInfoSuccess="updateUserInfoEmit">
      </updateUserInfoDialog>

    </div>
  </div>
</template>

<script type="text/javascript">
  import userRight from '../userManager/userRight.vue'
  import userDevice from '../userManager/userDevice.vue'
  import addNewUserDialog from '../userManager/addNewUserDialog.vue'
  import deviceSelectDialog from '../userManager/deviceSelectDialog.vue'
  import rightSelectDialog from '../userManager/rightSelectDialog.vue'
  import updateUserInfoDialog from '../userManager/updateUserInfoDialog.vue'
  import roleList from '../userManager/roleList.vue'
  import userManagerStore from '../userManager/userManagerStore.js'
  export default {
    components: {
      userRight,
      userDevice,
      addNewUserDialog,
      deviceSelectDialog,
      rightSelectDialog,
      updateUserInfoDialog,
      roleList
    },
    props: [],
    data () {
      return {
        tokenTimeData: {
          ONE: '1天',
          SEVEN: '7天',
          THIRTY: '30天',
          PERPETUAL: '永久',
        },
        //  heights: document.getElementById('myareaContainernoe').clientHeight-200,//屏幕高度 - 导航栏高度
        heights: ((document.getElementById('app').clientHeight-100)/2)-100,//屏幕高度 - 导航栏高度
        filterText: "",
        tabPage: 0,
        nowIndex: 0,
        newUserData: undefined,  // 新建用户信息对象
        newUserRoleIds: undefined,  // 新建用户的角色ids
        newUserDeviceNos: undefined,  // 新加用户选中的设备ids
        newUserRolesRights: undefined, // 新建用户选择角色的权限
        newUserRightIds: undefined,  // 新建用户的权限字符串ids
        addUserResponDatas: [],
        defaultProps: {
          children: 'next',
          label: 'name'
        },
        newDataList: [],
        defaultExpanded: [],
        defaultDevice: "",
        selectedRows: []

      }
    },
    created () {},
    mounted () {
      if(this.dataList&&this.dataList.length!=0) {
        this.$nextTick(() => {
          this.defaultExpanded=[this.dataList[0].id]
          this.defaultDevice=this.dataList[0].id
          //默认选中
          this.$refs['tree'].setCurrentKey(this.defaultDevice);
        })
      }
      if(this.nowUnitUserList&&this.nowUnitUserList.length!=0) {
        this.$nextTick(() => {
          this.$refs.singleTable.setCurrentRow(this.nowUnitUserList[0])
        })
      }
    },
    destroyed () {},
    computed: {
      userId () {
        var userInfo=this.$store.userStore.state.nowUserInfo
        return userInfo.userId
      },
      columns () {
        return [{name: '用户名称',key: 'username',weight: 1.5},{name: '登录名',key: 'usercode',weight: 1.5},{name: '令牌有效时间',key: 'tokenTime',weight: 2.5},{name: '卡号',key: 'rfid',weight: 1.5},{name: '邮箱地址',key: 'emailaddress',weight: 2},{name: '手机号',key: 'mobile',weight: 1.5},{name: '座机号码',key: 'telephone',weight: 1},{name: '备注',key: 'memo',weight: 2}]
      },
      pageLen () {
        return this.nowUnitUserList.length<20? this.nowUnitUserList.length:20
      },
      nowPage () {
        // 按照页码来返回当前应该显示的列表
        var list=this.nowUnitUserList.filter((item,index) => {
          return index>=this.nowIndex*this.pageLen&&index<(this.nowIndex+1)*this.pageLen
        })
        return list
      },
      dataList () {
        var data=this.$store.unitStore.getters.getUnitTree
        // var data = this.$store.deviceStore.getters.getReadDeviceTree
        this.newDataList=data
        return isempty(data)? []:[data]
      },
      allRightList () {
        return userManagerStore.state.allRightList
      },
      nowUnitUserList () {
        return userManagerStore.state.userList
      },
      userSelectedRoles () {
        return userManagerStore.state.nowUserRoleIds
      },
      nowCheckedUnit () {
        return userManagerStore.state.nowUnit
      },
      userSelected () {
        return userManagerStore.state.nowUser
      }
    },
    watch: {
      nowUnitUserList(){
        
        this.$nextTick(() => {
        this.$refs.singleTable.doLayout()
      })
      },
      filterText (val) {
        this.$refs.tree.filter(val);
      },
      addUserResponDatas () {
        if(this.addUserResponDatas.length>=3) {
          var result=this.addUserResponDatas.filter(item => {
            return !item.status
          })
          if(result.length>0) {
            var message=[]
            for(let i=0;i<result.length;i++) {
              message.push(result[i].message)
            }
            this.$dialogMethod.showMessage(message.join(','))
          } else {
            this.$dialogMethod.showMessage('添加用户成功')
          }
          this.addUserResponDatas=[]
        }
      },
      newDataList (val) {
        // console.log("侦听器",val);
        if([val].length!=0) {
          this.checkItem(val)
        }
      },
      dataList () {
        // console.log("侦听3");
      }

    },
    methods: {
      // 树形筛选
      filterNode (value,data) {
        if(!value) return true;
        return data.name.indexOf(value)!==-1;
      },
      // 分页切换
      tabPageChange (i) {
        if(this.tabPage==i) {
          return
        }
        if(i==0) {
          this.tabPage=i
          this.$refs.userDeviceView.resetDatas()
        } else {

          this.tabPage=i
          this.$refs.userRightView.coverCheckedIds()
        }
      },
      // 选中公司事件
      checkItem (item) {
        // console.log("item",item);
         userManagerStore.commit('setUnit',item)
         return
        if(this.nowCheckedUnit.id == undefined || this.nowCheckedUnit.id != item.id) {
          userManagerStore.commit('setUnit',item)
        }
      },
      handleCurrentChange (item) {

        if(item==undefined) {
          userManagerStore.commit('setUser',{})
        } else if(this.userSelected.id==undefined||this.userSelected.id!=item.id) {
          userManagerStore.commit('setUser',item)
        }
      },
      // 选中用户事件
      selectUser (item) {
        // console.log("选中用户",item);
        if(item==undefined) {
          userManagerStore.commit('setUser',{})
        } else if(this.userSelected.id==undefined||this.userSelected.id!=item.id) {
          userManagerStore.commit('setUser',item)
        }
      },
      clickTableHead () {
        userManagerStore.commit('setUser',{})
      },
      // 根据角色获取绑定的权限
      getRightsByRoleIds () {
        if(isempty(this.newUserRoleIds)) {
          this.newUserRolesRights={pcmDefault: [],appRight: [],menuRight: []}
          this.openRightSelectDialog()
          return
        }
        this.$api.menuApi.getRightsByRoleIds(this.newUserRoleIds,res => {
          this.newUserRolesRights=res
          this.openRightSelectDialog()
        },failure => {
          this.$dialogMethod.showMessage(failure)
        })
      },
      // 添加用户
      addNewUser () {
        if(this.nowCheckedUnit==undefined) {
          this.$dialogMethod.showMessage('请选择组织后再添加用户')
          return
        }
        this.$refs.addNewUserDialog.open('添加用户',(userData,roleIds) => {
          this.newUserData=userData
          this.newUserRoleIds=roleIds
          this.$refs.deviceSelectDialog.open('设备权限',respon => {
            this.newUserDeviceNos=respon
            this.getRightsByRoleIds()
          })
        })
      },
      // 打开选择用户权限弹窗
      openRightSelectDialog () {
        this.$refs.rightSelectDialog.open('用户权限',copy(this.newUserRolesRights),respon => {
          this.newUserRightIds=respon
          // 信息填写完毕创建新用户
          if(this.newUserData.emailpsw==''||this.newUserData.emailpsw==null||!this.newUserData.emailpsw) {
            var emailpsw=null
          } else {
            var emailpsw=hex_md5(this.newUserData.emailpsw)
          }
          this.$api.userApi.saveUser('',this.newUserData.username,this.newUserData.usercode,hex_md5(this.newUserData.password),this.newUserData.mobile,this.newUserData.telephone,this.nowCheckedUnit.id,this.newUserData.emailaddress,emailpsw,undefined,undefined,this.newUserData.memo,this.newUserRoleIds,this.newUserData.isSSO,undefined,this.newUserData.tokenTime,saveRespon => {
            var newUserId=saveRespon.id
            // 第二步绑定设备权限
            this.bindUserAndDevice('view',newUserId,this.newUserDeviceNos.view)
            this.bindUserAndDevice('edit',newUserId,this.newUserDeviceNos.edit)
            // 第三步绑定用户权限
            this.bindUserAndRight(newUserId,this.newUserRightIds)
            // 获取新的用户列表
            userManagerStore.commit('getUsersByUnitId',this.nowCheckedUnit.id)
          },err => {
            this.$dialogMethod.showMessage("添加用户失败！")
          })
        })
      },
      // 删除用户
      deleteUser () {
        if(this.userSelected.id==undefined) {
          this.$dialogMethod.showMessage('请先选中要删除的用户')
          return
        }
        this.$confirm('是否删除此用户','提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.userApi.deleteUserById(this.userSelected.id,res => {
            this.$dialogMethod.showMessage('删除用户信息成功！')
            userManagerStore.commit('getUsersByUnitId',this.nowCheckedUnit.id)
          },err => {
            this.$dialogMethod.showMessage(err)
          })
        }).catch(() => {
          // ...
        });

      },
      // 更新用户信息
      updateUserInfo () {
        if(this.userSelected.id==undefined) {
          this.$dialogMethod.showMessage('请先选中要修改信息的用户')
          return
        }
        this.$refs.updateUserInfoDialog.open('修改用户信息',this.userSelected,copy(this.userSelectedRoles))
      },
      updateUserInfoEmit (passwordChange) {
        if(passwordChange&&this.userSelected.id==this.userId) {
          this.logout()
        } else {
          userManagerStore.commit('getUsersByUnitId',this.nowCheckedUnit.id)
        }
      },
      // 绑定用户与权限
      bindUserAndRight (userId,rightIds) {
        this.$api.userApi.bindUserAndRight(userId,rightIds,res => {
          this.addUserResponDatas.push({step: 3,status: true,message: res})
        },err => {
          this.addUserResponDatas.push({step: 3,status: false,message: err})
        })
      },
      // 绑定用户与设备权限
      bindUserAndDevice (type,userId,deviceNos) {
        this.$api.userApi.bindUserAndDevice(type,userId,deviceNos,res => {
          if(type=='view') {
            this.addUserResponDatas.push({step: 1,status: true,message: res})
          } else if(type=='edit') {
            this.addUserResponDatas.push({step: 2,status: true,message: res})
          }
        },err => {
          if(type=='view') {
            this.addUserResponDatas.push({step: 1,status: false,message: err})
          } else if(type=='edit') {
            this.addUserResponDatas.push({step: 2,status: false,message: err})
          }
        })
      },
      saveEdit () {
        if(this.tabPage==0) {
          // 保存用户权限
          // console.log("用户权限");
          this.$refs.userRightView.saveEdit()
        } else if(this.tabPage==1) {
          // console.log("设备权限");
          // 保存设备权限
          this.$refs.userDeviceView.saveEdit()
        }
      },
      logout () {
        // this.$store.menuStore.commit('clear')
        // this.$dialogMethod.showLoading("正在注销...")
        // this.$api.userApi.logout(respon => {
        //   //清理所有缓存
        //   toLogin()
        // })
      }
    }
  }
</script>

<style scoped lang="scss">
  .newuserManager {
    .con {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      display: flex;
    }
  }

  .tree-left {
    width: 300px;
    height: 100%;
    padding: 12px;
    box-sizing: border-box;
    background-color: #fff;
    margin-right: 8px;


  }

  :deep(.el-table__body tr.current-row>td) {
    background-color: #d2eaff !important;
  }

  .right-table {
    width: calc(100% - 3.08rem);
    height: 100%;
    box-sizing: border-box;
    position: relative;

    .myareaContainer {
      padding: 12px 20px 20px 20px;
      box-sizing: border-box;
      width: 100%;
      background-color: #fff;
    }

  }

  :deep(.infoListBody ){
    height: 360px;
    background-color: #FFFFFF;
  }

  :deep(.el-scrollbar .el-scrollbar__wrap) {
    overflow-x: hidden;
  }

  :deep(.scroll) {
    height: 100%;
  }

  :deep(.el-scrollbar__wrap .el-scrollbar__view) {
    white-space: nowrap;
    display: inline-block;
  }

  .viewEditUsers {
    height: calc(100% - 54px);
    background: #fff;
    // padding: 12px;
    box-sizing: border-box;
  }

  :deep(.roleBox) {
    color: #999999;
  }





  .areaTitle {
    font-size: .14rem;
    font-weight: 600;
    line-height: 16px;
    border-left: solid 4px #3D7EFF;
    padding-left: 8px;
    margin-bottom: 8px;
  }

  .usersInfoRole {
    overflow: hidden;
  }

  .tabsHeader {
    margin-bottom: 12px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .tabBtnsContainer {
    float: left;

    // border: solid 2px #D1D1D1;
    // border-radius: 16px;
    span {
      cursor: pointer;
      font-weight: bold;
      font-size: 16px;
      display: inline-block;
      padding-bottom: 5px;
      margin-right: 20px;
      color: #999999;

    }
  }



  .tabBtnsContainer>.tabActive {
    // background: #3D7EFF;
    color: #529FFF;
    border-bottom: 2px solid #529FFF;
    // color: #2a8e7c;
    // border-bottom: 2px solid #2a8e7c;

  }

  .saveEditBtn {
    float: right;
    width: 110px;
    height: 32px;
    background: #3D7EFF;
    color: #FFFFFF;
    border-radius: 16px;
    margin-top: 1px;
    outline: none;
  }

  .usersInfoList {
    float: left;
    width: calc(100% - 252px);
  }

  .trActive {
    background: #5979C9;
  }

  .rolesList {
    float: right;
    width: 240px;
  }

  .rolesList input {
    vertical-align: middle;
    margin-right: 2px;
  }
</style>